// pages/user/user.js
import {
    Address
} from './editAddress-model.js';

const app = getApp()
const $address = new Address()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: {},
        dialogShow: false,
        threeArea: {
            provice: null,
            city: null,
            area: null
        },
        hasCity: false,
        hasArea: false,
        editAddress: null,
        editRegion: [],
        addressList: null,
        isShowPopup: false,
        tips: '',
        toggleWord: '新增',
        editId: '',
        loadDone: false,
        editStatusReset: false,
        type: '',
        orderId: '',
        addressId: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options)
        let province, city, area;
        let that = this
        let userInfo = wx.getStorageSync('userInfo')
        wx.showLoading({
            title: '加载中',
        })
        if (options.type == 'sel') {
            // 选择订单地址的情况
            this.setData({
                editId: options.id,
                type: options.type,
                orderId: options.orderId,
                addressId: options.addressId
            })
        } else if (options.type == 'change') {
            // 修改订单地址的情况
            this.setData({
                type: options.type,
                orderId: options.orderId,
            })
        } else {
            this.setData({
                editId: options.id,
            })
        }

        let provice = {
            "data": {
                "pid": "0"
            }
        }
        // 获取省一级 pid 0
        if (options.type != 'change') {
            $address.getThree(provice, res => {
                if (res.status) {
                    that.setData({
                        'threeArea.provice': res.data
                    })
                    let parmas = {
                        "data": {
                            "id": options.id + ""
                        }
                    }
                    // 省的请求后循环查找省的名称
                    let provicePromise = new Promise((reslove, reject) => {
                        $address.getUserAddressById(parmas, res => {
                            console.log(res)
                            let data = res.data
                            if (res.status) {
                                console.log(res.data)
                                // 当前的省市区id,给最上乘赋值
                                province = data.province
                                city = data.city
                                area = data.area
                                this.data.threeArea['provice'].forEach((val, i) => {
                                    if (val.id == province) {
                                        reslove(val.id)
                                        let detailedAddress = res.data.detailedAddress.split(' ')
                                        res.data.detailedAddress = detailedAddress[detailedAddress.length - 1]
                                        this.setData({
                                            editAddress: res.data,
                                            'editRegion[0]': {
                                                name: val.name,
                                                index: i
                                            }
                                        })
                                    }
                                })
                            } else {
                                wx.hideLoading()
                                wx.showToast({
                                    title: '服务器错误',
                                    icon: 'none'
                                })
                            }
                        })
                    })
                    // 请求后循环查找市的名称

                    provicePromise.then(pRes => {
                        console.log('res22', pRes)
                        let cityPromise = new Promise((reslove, reject) => {
                            // 获取市
                            let cityParams = {
                                "data": {
                                    "pid": pRes
                                }
                            }
                            $address.getThree(cityParams, cityRes => {
                                if (cityRes.status) {
                                    this.setData({
                                        'threeArea.city': cityRes.data,
                                    })
                                    this.data.threeArea['city'].forEach((cityVal, cIdx) => {
                                        if (cityVal.id == city) {
                                            this.setData({
                                                'editRegion[1]': {
                                                    name: cityVal.name,
                                                    index: cIdx
                                                }
                                            })
                                            reslove(cityVal.id)
                                        }
                                    })
                                } else {
                                    wx.hideLoading()
                                    wx.showToast({
                                        title: '服务器错误',
                                        icon: 'none'
                                    })
                                }
                            })
                        })

                        // 请求后循环查找区域的名称
                        cityPromise.then(aRes => {
                            console.log('33', aRes)
                            let areaParams = {
                                "data": {
                                    "pid": aRes
                                }
                            }
                            $address.getThree(areaParams, areaRes => {
                                wx.hideLoading()
                                if (areaRes.status) {
                                    this.setData({
                                        'threeArea.area': areaRes.data,
                                    })
                                    this.data.threeArea['area'].forEach((areaVal, aIdx) => {
                                        if (areaVal.id == area) {
                                            this.setData({
                                                'dialogShow': true,
                                                'editRegion[2]': {
                                                    name: areaVal.name,
                                                    index: aIdx
                                                },
                                                hasCity: false,
                                                hasArea: false
                                            })
                                        }
                                    })
                                } else {
                                    wx.hideLoading()
                                    wx.showToast({
                                        title: '服务器错误',
                                        icon: 'none'
                                    })
                                }
                            })
                        })
                    })
                } else {
                    wx.hideLoading()
                    wx.showToast({
                        title: '服务器错误',
                        icon: 'none'
                    })
                }
            })
        } else {
            // 修改订单地址的情况
            $address.getDetailList({
                data: {
                    "orderId": options.orderId,
                    "storeNo": "S00000001"
                }
            }, res => {
                if (res.status) {
                    let data = res.data
                    this.setData({
                        editAddress: {
                            contacts: data.contacts,
                            mobilePhone: data.mobilePhone,
                            detailedAddress: data.detailedAddress
                        }
                    })
                } else {
                    wx.showToast({
                        title: '服务器错误',
                        icon: 'none'
                    })
                }
                wx.hideLoading()
            })
        }
    },
    preventD(e) {
        return;
    },
    // 省选择
    proviceChange(e) {
        console.log(e.detail.value)
        let val = e.detail.value
        let provice = this.data.threeArea.provice[val]
        let that = this
        let params = {
            "data": {
                "pid": provice.id
            }
        }
        $address.getThree(params, res => {
            if (res.status) {
                that.setData({
                    'threeArea.city': res.data,
                    'editRegion[1]': '',
                    'editRegion[2]': '',
                })
            }
        })
        this.setData({
            'editRegion[0]': {
                id: provice.pid,
                name: provice.name,
                index: val
            },
            hasCity: false,
            hasArea: true

        })
        if (this.data.toggleWord == '编辑') {
            this.setData({
                // 'editAddress.detailedAddress': '',
                editStatusReset: true
            })
        }
    },
    // 市选择
    cityChange(e) {
        console.log(e.detail.value)
        let that = this
        let val = e.detail.value
        let city = this.data.threeArea.city[val]
        let params = {
            "data": {
                "pid": city.id
            }
        }
        $address.getThree(params, res => {
            if (res.status) {
                that.setData({
                    'threeArea.area': res.data,
                    'editRegion[2]': '',

                })
            }
        })
        this.setData({
            'editRegion[1]': {
                id: city.pid,
                name: city.name,
                index: val
            },
            hasArea: false,
        })

        this.setData({
            // 'editAddress.detailedAddress': '',
            editStatusReset: true
        })

    },
    // 区域选择
    areaChange(e) {
        console.log(e.detail.value)
        let val = e.detail.value
        let area = this.data.threeArea.area[val]

        this.setData({
            'editRegion[2]': {
                id: area.pid,
                name: area.name,
                index: val
            },
        })

        this.setData({
            // 'editAddress.detailedAddress': '',
            editStatusReset: true
        })

    },
    // 新增编辑地址
    formSubmit(e) {
        console.log(e)
        let formdata = e.detail.value
        let that = this
        let data = this.data

        console.log(formdata)
        if (formdata.acceptName.trim() == '') {
            wx.showToast({
                title: '请输入收货人',
                icon: 'none'
            })
        } else if (formdata.acceptName.length > 50) {
            wx.showToast({
                title: '收货人不超过50个字',
                icon: 'none'
            })
        } else if (formdata.phone.trim() == '' || !/^((0\d{2,3}-\d{7,8})|(1[345678]\d{9}))$/.test(formdata.phone)) {
            wx.showToast({
                title: '请输入正确的联系电话',
                icon: 'none'
            })
        } else if (data.type != 'change' && (formdata.city == null || formdata.provice == null || formdata.provice === '' || formdata.city === '')) {
            wx.showToast({
                title: '请选择省市',
                icon: 'none'
            })
        } else if (formdata.detail.trim() == '') {
            wx.showToast({
                title: '请输入详细地址',
                icon: 'none'
            })
        } else if (formdata.detail.length > 100) {
            wx.showToast({
                title: '收货地址不超过100个字',
                icon: 'none'
            })
        } else if (data.type == 'change') {
            // 修改订单地址的情况
            wx.showModal({
                title: '提示',
                content: '确定修改吗？',
                success(res) {
                    if (res.confirm) {
                        let params = {
                            data: {
                                orderId: data.orderId,
                                contacts: formdata.acceptName,
                                mobilePhone: formdata.phone,
                                detailedAddress: formdata.detail
                            }
                        }
                        wx.showLoading({
                            title: '加载中...',
                        })
                        $address.updateOrderRedAddress(params, res => {
                            wx.hideLoading()
                            if (res.status) {
                                var pagelist = getCurrentPages();
                                if (pagelist.length > 1) {
                                    //获取上一个页面实例对象
                                    var prePage = pagelist[pagelist.length - 2];
                                    prePage.onLoad({
                                        orderId: data.orderId,
                                    });

                                    setTimeout(() => {
                                        wx.navigateBack({
                                            delta: 1
                                        })
                                    }, 500)

                                }
                            } else {
                                wx.showToast({
                                    title: '服务器错误',
                                    icon: 'none'
                                })
                            }
                        })
                    }
                }
            })
        } else {
            let threeArea = data.threeArea
            let area = threeArea.area[formdata.area] != null ? threeArea.area[formdata.area].name : '';

            let PCA = threeArea.provice[formdata.provice].name + ' ' + threeArea.city[formdata.city].name + ' ' + area + ' '
            console.log(PCA)
            
            let areaId = data.threeArea.area[formdata.area] != null ? data.threeArea.area[formdata.area].id : '';
            let params = {
                data: {
                    "province": "" + data.threeArea.provice[formdata.provice].id,
                    "city": "" + data.threeArea.city[formdata.city].id,
                    "area": "" + areaId,
                    "detailedAddress": PCA + formdata.detail,
                    "contacts": formdata.acceptName,
                    "mobilePhone": formdata.phone
                }
            }

            console.log('params', params)
            wx.showModal({
                title: '提示',
                content: '确认保存吗？',
                success: function (res) {
                    if (res.confirm) {
                        params.data.id = data.editId
                        $address.updateUserAddress(params, res2 => {
                            console.log(res2)
                            let status = res2.status
                            if (status) {
                                wx.showToast({
                                    title: '编辑成功',
                                    icon: 'success',
                                    duration: 1500,
                                    success() {
                                        var pagelist = getCurrentPages();
                                        if (pagelist.length > 1) {
                                            //获取上一个页面实例对象
                                            var prePage = pagelist[pagelist.length - 2];
                                            if (data.type == 'sel') {
                                                // 如果是选择切换地址
                                                prePage.onLoad({
                                                    orderId: data.orderId,
                                                    addressId: data.addressId
                                                });
                                            } else {
                                                prePage.onLoad();
                                            }

                                            wx.navigateBack({
                                                delta: 1
                                            })

                                        }
                                    }
                                })
                            } else {
                                wx.hideLoading()
                                wx.showToast({
                                    title: '服务器错误',
                                    icon: 'none'
                                })
                            }
                        })
                    } else if (res.cancel) {
                        console.log('用户点击取消')
                    }
                }
            })
        }
    },
})